package com.foohoo.benchmark.grammar;

import lombok.extern.slf4j.Slf4j;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 测试算术运算符和位运算符的性能差异
 * Benchmark                                                 Mode  Cnt   Score    Error  Units
 * ArithmeticOperatorsVsBitwiseOperators.withDivision        avgt    5  47.360 ±  1.792  ns/op
 * ArithmeticOperatorsVsBitwiseOperators.withLeftShift       avgt    5  46.412 ±  1.028  ns/op
 * ArithmeticOperatorsVsBitwiseOperators.withMultiplication  avgt    5  46.496 ±  2.492  ns/op
 * ArithmeticOperatorsVsBitwiseOperators.withRightShift      avgt    5  56.488 ± 30.738  ns/op
 * 一句话结论: 尽管理论上位运算会比算术运算快得多，但实际上编译器会在编译阶段解决这个问题，所以，按真实的业务意图来写代码就好
 *
 * @author mzdbxqh
 * @date 2020-10-28 13:22
 **/
@Slf4j
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(1)
@Threads(1)
@State(Scope.Benchmark)
public class ArithmeticOperatorsVsBitwiseOperators {

	private long targetInt;

	@Setup(Level.Invocation)
	public void initialize() {
		Random random = new Random();
		targetInt = random.nextLong();
	}

	@Benchmark
	public void withMultiplication(Blackhole bh) {
		bh.consume(targetInt * 1024 * 1024);
	}

	@Benchmark
	public void withLeftShift(Blackhole bh) {
		bh.consume(targetInt << 20);
	}

	@Benchmark
	public void withDivision(Blackhole bh) {
		bh.consume(targetInt / (1024 * 1024));
	}

	@Benchmark
	public void withRightShift(Blackhole bh) {
		bh.consume(targetInt >> 20);
	}
}
